import org.codehaus.groovy.grails.commons.ConfigurationHolder as CH

class UserService {
    boolean transactional = true

    def fileService

    def add(file, params){
    	def instance
    	//	Miramos si es para hacer un update o un save
    	if (params.id) {
    		instance = User.get(params.id)
    		instance.properties = params
    	} else {
    		instance = new User(params)
    	}
    	
    	if(params.password != params.repeatPassword) {
    		instance.errors.rejectValue("password", "password.not.equals", null, "LOS PASSWORDS TIENEN QUE SER IGUALES")
    	}
    	
    	if(!instance.hasErrors()) {
			if(!file.isEmpty()) {
				def validate = fileService.validate(file, CH.config.comics.maxSizeAvatar)
	    		if(validate.ext != null) {
	    			def randomName = null
	    			def i = 0
	    			while(randomName == null && i < 3) {
	    				i =  i + 1
	    				randomName = fileService.addFile(file, "/user/", validate.ext)
	    			}
	    			
	    			if (randomName == null) {		//	No ha podido guardar el fichero en N intentos
	    				instance.errors.rejectValue('pathFile',null,'no se ha podido guardar el fichero')
	    				log.debug "No se ha podido guardar la imagen con el nombre: ${randomName}.${validate.ext} y parametros: ${instance.toString()}"
		    			return [instance:instance]
	    			}
	    			
	    			instance.nameFile = randomName + "." + validate.ext 
	    			
	    		} else {
	    			instance.errors.rejectValue('',null,validate.error)
	    			return [instance:instance]
	    		}
			}
	    	
	    	instance.save()
    	}
		return [instance:instance]
    }
    
    
    def delete(params) {
    	def instance = User.get(params.id)
		
    	if (instance) {
			def result = null
			def i = 0
			while(result == null && i < 3) {
				i =  i + 1
				result = fileService.removeFile("/user/", instance.nameFile)
			}
			
			if (result == null) {		//	No ha podido guardar el fichero en N intentos
				instance.errors.rejectValue('',null,'no se ha podido borrar el fichero')
				log.debug "No se ha podido borrar la imagen con el nombre: ${instance.nameFile} y parametros: ${instance.toString()}"
			
			} else { instance.delete() }
			
			return [instance:instance]	    			
	    	
    	} else { return null }
    }
    
    
    def update(file, params) {
    	def instance = User.get(params.id)
    	if (instance) {
            if (params.version) {
                def version = params.version.toLong()
                if (instance.version > version) {
                    instance.errors.rejectValue("version", "user.optimistic.locking.failure", "Another user has updated this User while you were editing")
                    return instance
                }
            }
            
            //	Si no han modificado el password, ponemos los que tenia
        	if (params.password == "") {
        		params.password = instance.password
        		params.repeatPassword = instance.password
        	}
        	
            instance.properties = params

            if(file != null && !file.isEmpty()) {
            	def result = ""
            	if(instance.nameFile != null && instance.nameFile != "") { result = delete(params) }
            	
            	if (result == null) { 
            		throw new Exception()
            	}       
            	
            	result = add(file, params)
            	if (result == null || result.instance.hasErrors()) {
//            		println "aa " + result.instance.errors.each() {println it} 
            		instance = result.instance
            	}
            	return result.instance
            } 
            	
            instance.save()
        	return instance
        }
        else { return null }
    }
}
